import axios from 'axios';
import {Message} from "element-ui";
/***
 * 如果token失效跳到首页
 * 会经过router拦截
 * 此时已把登录token删除 所以此时会被拦截去登录页
 */
/***
 * 初始化http请求拦截
 */
export function initHttpInterceptor(instance) {
    instance.interceptors.request.use((v) => {
        return v;
    });
    instance.interceptors.response.use(
        async response => {
            const {success,message} = response.data;

            if (!success) {
                Message.error(message);
                throw new Error("请求错误");
            }
            return response;
        },
        error => {
            const {code, msg} = error.response.data;
            if (code !== 200) return alert("请求失败")
        });
}
/***
 * 如果没有登录则不能访问其他路由
 */
export function initRouterInterceptor(router) {
    router.beforeEach((from, to, next) => {
        const isLogin = sessionStorage.getItem("X-Access-Token");
        if (!isLogin && !from.path.match(/login|register/)) {
            return next({path: "/login", query: from.query});
        }
        next();
    });
}
